package com.chenhy.springbootvuesmbms.service;

import com.chenhy.springbootvuesmbms.pojo.CommonResult;
import com.chenhy.springbootvuesmbms.pojo.User;
import com.chenhy.springbootvuesmbms.security.LoginUser;
import com.chenhy.springbootvuesmbms.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServerImpl implements LoginServer {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public CommonResult login(User user) {
        // AuthenticationManager进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getId(),user.getUserPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        // 如果认证不通过，就返回不通过的结果
        if (Objects.isNull(authentication)){
//            throw new RuntimeException("登陆失败");
            System.out.println("认证不通过，登陆失败");
            return new CommonResult(444,"登录失败");
        }
        // 如果认证通过，使用userId生成一个JWT，JWT返回给前端
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        String userID = loginUser.getId().toString();
        // 将这个用户的ID加密成JWT字符串
        String jwt = JwtUtil.createJWT(userID);
        // 把完整的用户信息存入redis，userId为key
        redisTemplate.opsForValue().set("Login:"+loginUser.getId(),loginUser);
        HashMap map = new HashMap();
        map.put("token",jwt);

        return new CommonResult(200,"登陆成功",map);
    }

    @Override
    public CommonResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        redisTemplate.delete("Login:"+loginUser.getId());
        return new CommonResult(200,"成功退出登录");
    }
}
